package TCP.TCP8;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServer {

    private ServerSocket listensocket;

    public TcpServer(int port) throws IOException {
        this.listensocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动~");
        ExecutorService threadPool = Executors.newCachedThreadPool();
        while(true) {
            Socket clientSocket = listensocket.accept();
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processClient(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    private void processClient(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线~", clientSocket.getInetAddress(),
                clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner input = new Scanner(inputStream);
            PrintWriter output = new PrintWriter(outputStream);
            while(true) {
                //1.接收客户端请求
                if(!input.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线~", clientSocket.getInetAddress(),
                            clientSocket.getPort());
                    break;
                }
                String request = input.next();
                //2.根据请求计算响应(回显服务器)
                String response = process(request);
                //3.发送响应给客户端
                output.println(response);
                output.flush();
                //4.打印日志
                System.out.printf("[%s:%d] req: %s, resp: %s\n", clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(), request, response);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServer tcpServer = new TcpServer(8080);
        tcpServer.start();
    }

}
